package com.gpmall.commons.lock.extension.annotation;

import java.util.Comparator;

/**
 * @author z.w
 * @version v1.0
 * @apiNote desc
 * @date 2021/12/16 11:25
 */
public class SpiActivateComparator implements Comparator<Object> {

    public static final Comparator<Object> COMPARATOR = new SpiActivateComparator();

    @Override
    public int compare(Object o1, Object o2) {
        if (o1 == null && o2 == null) {
            return 0;
        }
        if (o1 == null) {
            return -1;
        }
        if (o2 == null) {
            return 1;
        }
        if (o1.equals(o2)) {
            return 0;
        }

        int n1 = parseActivate(o1.getClass());
        int n2 = parseActivate(o2.getClass());
        // never return 0 even if n1 equals n2, otherwise, o1 and o2 will override each other in collection like HashSet
        return n1 > n2 ? 1 : -1;
    }

    private int parseActivate(Class<?> clazz) {
        if (clazz.isAnnotationPresent(LockActivate.class)) {
            LockActivate activate = clazz.getAnnotation(LockActivate.class);
            return activate.order();
        }
        return 0;
    }
}
